package com.lottery.web.interceptor;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.lottery.common.util.Constant;
import com.lottery.web.model.Account;

/**
 * 过滤下jsp页面
 * @author linzhimou
 */
public class JspFilter implements Filter{
	
	private static Logger logger = Logger.getLogger(JspFilter.class);

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpSession session = request.getSession();

		// 获得用户请求的URI
		String path = request.getRequestURI();
		String contextPath = request.getContextPath();
		
		logger.info(path);
		
		if(!excludeUrl(path)){
			if(session == null){
				logger.info("-----session is null-----");
				response.sendRedirect(contextPath + "/static/layout/login.jsp");
				return;
			}
			
			Account account = (Account) session.getAttribute(Constant.USER);
			if(account == null){
				logger.info("-----account is null-----");
				response.sendRedirect(contextPath + "/static/layout/login.jsp");
				return;
			} else {
				String role = account.getRole();
				//校验角色对应的页面
			}
		}
		
		filterChain.doFilter(servletRequest, servletResponse);
		return;
	}
	
	//排除的页面
	private boolean excludeUrl(String path){
		return path.endsWith("login.jsp");
	}
	
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}
	
	@Override
	public void destroy() {
		
	}
	
}
